package com.hunau.novel_reading.controller;

import com.hunau.novel_reading.common.BindingResultParseMessage;
import com.hunau.novel_reading.common.R;
import com.hunau.novel_reading.entity.Users;
import com.hunau.novel_reading.request.UsersLoginReq;
import com.hunau.novel_reading.request.UsersRegisterReq;
import com.hunau.novel_reading.request.UsersSeekReq;
import com.hunau.novel_reading.service.UserService;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/users")
public class UsersController {
    @Resource
    private UserService userService;

    @PostMapping("/login")
    public R login(@RequestBody @Valid UsersLoginReq users, BindingResult bindResult){
        if(bindResult.hasErrors()){
            return R.error().message(BindingResultParseMessage.parseDefaultMessage(bindResult));
        }
        Users u=userService.Login(users);
        return R.ok().data("users",u);
    }

    @PostMapping("/register")
    public R register(@RequestBody @Valid UsersRegisterReq users, BindingResult bindResult){
        if(bindResult.hasErrors()){
            return R.error().message(BindingResultParseMessage.parseDefaultMessage(bindResult));
        }
        String msg=userService.register(users);
        return R.ok().message(msg);
    }
    @PostMapping("/seek")
    public R seek(@RequestBody @Valid UsersSeekReq users, BindingResult bindResult){
        if(bindResult.hasErrors()){
            return R.error().message(BindingResultParseMessage.parseDefaultMessage(bindResult));
        }
        String password=userService.seek(users);
        return R.ok().data("password",password);
    }
    @PostMapping("/selectByUserId")
    public R selectByUserId(@RequestBody @Valid com.hunau.novel_reading.request.UsersSeekByUserId users, BindingResult bindResult){
        if(bindResult.hasErrors()){
            return R.error().message(BindingResultParseMessage.parseDefaultMessage(bindResult));
        }
        Users u=userService.selectByUserId(users);
        if(u==null)
            return R.error().message("用户不存在");
        return R.ok().data("users",u);
    }
}
